package com.kailing.bootBatch.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <h3>partitionjob</h3>
 * <p>foobat</p>
 *
 * @author : hduong
 * @version : 1.0
 * @date : 2019-12-18 10:17
 **/
public class FooBar {
    private int n;

    private ReentrantLock lock = new ReentrantLock();

    //2把锁来交替执行方法
    private Condition fooTurn = lock.newCondition();
    private Condition barTurn = lock.newCondition();


    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
        try {
            lock.lock();
            for (int i = 0; i < n; i++) {
                // printFoo.run() outputs "foo". Do not change or remove this line.
                barTurn.signal();
                printFoo.run();
                //唤醒bar
                //自己睡眠 : 等待被唤醒
                fooTurn.await();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void bar(Runnable printBar) throws InterruptedException{

        try {
            lock.lock();
            for (int i = 0; i < n; i++) {
                // printBar.run() outputs "bar". Do not change or remove this line.
                fooTurn.signal();
                printBar.run();
                //唤醒 fooBar
                //自己睡眠 不抢cpu
                barTurn.await();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
